import _ from 'lodash';
import Cookies from 'js-cookie';
import Crypto from 'crypto-js';

const userTheme = 'app-theme';
const TokenKey = 'app-token';
const themeKey = 'vFxMUxH15WnsUkaz';
const aesParamsKey = Crypto.enc.Utf8.parse(themeKey);
const iv = Crypto.enc.Utf8.parse(themeKey);
function encryptTheme(data) {
  const srcStr = Crypto.enc.Utf8.parse(_.isString(data) ? data : JSON.stringify(data || {}));
  const encryptStr = Crypto.AES.encrypt(srcStr, aesParamsKey, {
    mode: Crypto.mode.CTR,
    padding: Crypto.pad.Pkcs7,
    iv,
  });
  return encryptStr.ciphertext.toString().toUpperCase();
}
function decryptTheme(data) {
  try {
    const encryptedHexStr = Crypto.enc.Hex.parse(data);
    const srcStr = Crypto.enc.Base64.stringify(encryptedHexStr);
    const decryptStr = Crypto.AES.decrypt(srcStr, aesParamsKey, {
      mode: Crypto.mode.CTR,
      padding: Crypto.pad.Pkcs7,
      iv,
    });
    const decryptedStr = decryptStr.toString(Crypto.enc.Utf8);
    return JSON.parse(decryptedStr.toString()) || {};
  } catch (e) {
    return {};
  }
}

export function getToken() {
  return Cookies.get(TokenKey);
}

export function setToken(token) {
  return Cookies.set(TokenKey, token);
}

export function removeToken() {
  return Cookies.remove(TokenKey);
}

export function setTheme(themes) {
  const themeValues = encryptTheme(themes);
  localStorage.setItem(userTheme, themeValues);
}

export function getTheme() {
  try {
    const themes = decryptTheme(localStorage.getItem(userTheme));
    return _.isPlainObject(themes) ? themes : {};
  } catch (e) {
    return {};
  }
}
